<template>
    <div class="main_container">
        <el-row style="height: 40px;line-height: 40px;margin: 10px 20px 25px 20px;">
            <el-col :span="6">
                <el-radio-group v-model="filterType" @change="radioChange">
                    <el-radio label="1">按条件筛选</el-radio>
                    <el-radio label="2">按日期范围</el-radio>
                </el-radio-group>
            </el-col>
            <el-col :span="7" v-if="filterType=='1'">
                <el-select style="width: 280px;" v-model="date_order_type" placeholder="请选择"
                    @change="typeChange">
                    <el-option v-for="item in filterTypes" :key="'filter_'+item.value" 
                        :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-col>
            <el-col :span="7" v-else>
                <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                    v-model="dateRange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                    :picker-options="handleTime" @change="dateChange"
                    placeholder="请选择日期范围" style="width: 280px;" clearable></el-date-picker>
            </el-col>
            <el-col :span="7" style="display: flex;align-items: center;">
                <span style="font-size: 14px;color: #606266;width: auto;">客户名称：</span>
                <div class="choose_border" @click="showChooseCustomerAlert = true">
                    <span style="color: #c0c4cf;" v-if="!customer_name">请选择</span>
                    <span>{{ customer_name }}</span>
                    <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('customer')"></i> -->
                </div>
            </el-col>
        </el-row>
        <div class="common_line"></div>
        <el-row style="padding: 5px 14%;">
            <el-col :span="6" class="flex_div">
                <span class="top_title">期初结余</span>
                <span class="money" :class="topData.start_money<0?'red':'green'">{{ topData.start_money }}</span>
            </el-col>
            <el-col :span="6" class="flex_div">
                <span class="top_title">新增欠款</span>
                <span class="money" :class="topData.add_money<0?'red':'green'">{{ topData.add_money }}</span>
            </el-col>
            <el-col :span="6" class="flex_div">
                <span class="top_title">已收欠款</span>
                <span class="money" :class="topData.sub_money<0?'red':'green'">{{ topData.sub_money }}</span>
            </el-col>
            <el-col :span="6" class="flex_div">
                <span class="top_title">期末合计</span>
                <span class="money" :class="topData.end_money<0?'red':'green'">{{ topData.end_money }}</span>
            </el-col>
        </el-row>
        <div class="common_line"></div>
        
        <el-table border :data="orders" show-summary :summary-method="getSummaries" style="margin-top: 15px;">
            <el-table-column label="单据类型" align="center" prop="order_type" />
            <el-table-column label="单据编号" align="center" prop="corp_order_no" />
            <el-table-column label="日期" align="center" prop="orders_date" />
            <el-table-column label="已收" align="center" prop="sub_money_name" />
            <el-table-column label="新增" align="center" prop="add_money_name" />
            <el-table-column label="期末" align="center" prop="end_money_name" />
        </el-table>

         <!-- 选择客户 -->
        <choose-customer
            :showChooseCustomer="showChooseCustomerAlert"
            :selectUsers="customerList"
            @chooseOK="chooseCustomerOK"
            @hidden="showChooseCustomerAlert=false"
        ></choose-customer>
    </div>
</template>

<script>
import { customCheckOrder } from '@/api/statistics'
import { getCustomerList } from "@/api/cooperate";
import chooseCustomer from "@/components/chooseCustomer";

export default {
    name: 'shouldReceive',
    components: {
        chooseCustomer,
    },
    data() {
        return {
            showLoading: false,
            showChooseCustomerAlert: false,
            filterType: '1',  //1 按条件  2 按日期范围
            filterTypes: [
                {id: 1, label: '今日', value: 'cur_day'},
                {id: 2, label: '本周', value: 'cur_weak'},
                {id: 3, label: '本月', value: 'cur_month'},
                {id: 4, label: '本年', value: 'cur_year'}
            ],
            params: {
                corp: '',
                start_date: '',
                end_date: '',
                customer_id: '',
                date_order_type: 'cur_month'
            },
            date_order_type: 'cur_month',
            dateRange: [],
            customer_name: '',
            customerList: [],
            handleTime: {
                disabledDate(date) {
                    //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
                    return date.getTime() > Date.now();
                }
            },
            totalCount: 0,
            orders: [],
            topData: {
                start_money: '0.00',
                end_money: '0.00',
                add_money: '0.00',
                sub_money: '0.00'
            }
        }
    },
    created() {
        this.params.corp = this.$store.state.corpId
        let nowDate = new Date()
        this.params.start_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-01'
        if (this.$route.query.cusId){
            this.params.customer_id = this.$route.query.cusId
            this.customer_name = decodeURIComponent(this.$route.query.cusName)
            this.getData()
        }
    },
    methods: {
        // 补零
        add0(num) {
            if (parseInt(num) < 10){
                num = '0'+ num
            }
            return num
        },
        chooseCustomerOK(res) {
            this.params.customer_id = res.length ? res[0].id : ''
            this.customer_name = res.length ? res[0].name : ''
            // 获取当前URL
            let url = window.location.href;
            // 使用正则表达式去除参数部分
            let newUrl = url.replace(/\?.*/, '');
            // 更新URL
            window.history.replaceState({}, '', newUrl);
            this.getData()
            this.showChooseCustomerAlert = false
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] = sums[index].toFixed(2);
                } else {
                    sums[index] = '--';
                }
            });

            return sums;
        },
        // 获取数据
        getData() {
            var that = this
            customCheckOrder(this.params).then(res => {
                that.topData.start_money = res.data.start_money.toFixed(2)
                that.topData.end_money = res.data.end_money.toFixed(2)
                let add_money = 0, paid_money = 0;
                let lists = res.data.data_list.filter(item => {
                    item.sub_money = item.sub_money || 0
                    if (item.data_type == 'sale'){
                        item.order_type = '销售单'
                    }else if (item.data_type == 'return'){
                        item.order_type = '销售退单'
                    }else if (item.data_type == 'receipt'){
                        item.order_type = '收款单'
                    }
                    add_money = that.$common.plusFloat(add_money, item.add_money)
                    paid_money = that.$common.plusFloat(paid_money, item.sub_money)

                    item.end_money_name = item.end_money.toFixed(2)
                    item.add_money_name = item.add_money.toFixed(2)
                    item.sub_money_name = item.sub_money.toFixed(2)
                    return item
                })
                that.topData.add_money = add_money.toFixed(2)
                that.topData.sub_money = paid_money.toFixed(2)
                that.orders = lists
            })
        },
        radioChange(val) {
            if (val == '1'){
                this.typeChange(this.date_order_type)
            }else{
                this.dateChange(this.dateRange)
            }
        },
        typeChange(val) {
            if (!val) return
            if (!this.params.customer_id){
                this.$message.error('请选择客户')
                 return
            }

            let nowDate = new Date()
            if (val.indexOf("cur_")<0){
                this.params.start_date = nowDate.getFullYear()+'-01-01'
                if(val == 'day'){  //本月，28~31天
                    this.params.start_date = nowDate.getFullYear()+this.add0(nowDate.getMonth()+1)+'-01'
                }
            }else{
                this.params.start_date = ''
            }
            this.params.date_order_type = val

            this.getData()
        },
        dateChange(value) {
            if(value && value.length){
                this.params.start_date = value[0]
                this.params.end_date = value[1]
                this.params.date_order_type = 'customize_date'
                this.getData()
            }
            else{
                this.params.start_date = this.params.end_date = null
                this.params.date_order_type = ''
                this.tableData = []
            }
        },
        // 选择客户
        personChange(value) {
            if (value){
                let [ id, name ] = value.split('&&')
                this.params.customer_id = id
                this.customer_name = name
            }else{
                this.params.customer_id = ''
                this.customer_name = ''
            }
            // 获取当前URL
            let url = window.location.href;
            // 使用正则表达式去除参数部分
            let newUrl = url.replace(/\?.*/, '');
            // 更新URL
            window.history.replaceState({}, '', newUrl);
            this.getData()
        },
        remoteMethodWithCustomer(query) {
            if (query !== '') {
                this.showLoading = true
                getCustomerList({
                    corp: this.params.corp,
                    category: '',
                    search: query
                }).then(res => {
                    this.showLoading = false
                    this.customerList = res.data.data.customer_list.filter(item => {
                        item.label = item.name
                        item.value = item.id+'&&'+item.name
                        if (item.category_detail && item.category_detail.name){
                            item.label += ('（'+item.category_detail.name+'）')
                        }
                        return item
                    });
                })
            } else {
                this.customerList = []
            }
        },
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .flex_div {
        display: flex;
        flex-direction: column;
        align-items: center;
        .top_title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 14px;
        }
        .money {
            font-size: 22px;
            font-weight: bold;
            // color: red;
            &::before {
                content: '￥';
                font-size: 14px;
            }
        }
        .order {
            &::before {
                content: '';
            } 
        }
        .red {
            color: red;
        }
        .green {
            color: @blue;
        }
    }
</style>